package com.igeek.compus.test.menu.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.igeek.compus.test.menu.entity.Menu;
import com.igeek.compus.test.menu.service.MenuService;
import com.igeek.compus.test.system.Constants;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("menu")
public class MenuController {

    private final static Logger logger = Logger.getLogger(MenuController.class);

    @Autowired
    private MenuService menuService;

    @RequestMapping("list.do")
    @ResponseBody
    public Map list(Menu menu) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 业务代码，菜单信息查询
            PageInfo<Menu> menuList = menuService.getMenuListByPage(menu);
//            int count = menuService.getMenuListCount(menu);

            result.put(Constants.RETDATA, menuList.getList());
            result.put(Constants.COUNT, menuList.getTotal());

            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
        } catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }
        return result;
    }

    @RequestMapping("deleteMenuById.do")
    @ResponseBody
    public void deleteMenuById(Menu menu) {
        System.out.println(menu);
        menuService.deleteMenuById(menu);
    }

    @RequestMapping("deleteMenuList.do")
    @ResponseBody
    public Map<String, Object> deleteMenuList(String menuIds) {
        Map<String, Object> result = new HashMap<>();

        List<String> menuIdList = Arrays.asList(menuIds.substring(1, menuIds.length() - 1).split(","));

        // 2.执行业务
        try {
            if (menuService.deleteMenuList(menuIdList) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            } else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("addMenu.do")
    @ResponseBody
    public Map<String, Object> addMenu(Menu menu) {
        Map<String, Object> result = new HashMap<>();

        // 1.参数校验
        if(StrUtil.isEmpty(menu.getMenuName()) || StrUtil.isEmpty(menu.getUrl())
                || menu.getSerial() == null) {
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.PARAM_ERROR_MSG);
            return  result;
        }

        // 2.执行业务
        try {
            if(menuService.addMenu(menu) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("toMenuEdit.do")
    public ModelAndView toMenuEdit(Integer id) {
        // 通过id查询menu信息
        Menu menu = menuService.getMenuInfoById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("id", menu.getId());
        map.put("menuName", menu.getMenuName());
        map.put("imageUrl", menu.getImageUrl());
        map.put("url", menu.getUrl());
        map.put("serial", menu.getSerial());

        return new ModelAndView("/menu/menu_edit", map);
    }

    @RequestMapping("updateMenu.do")
    @ResponseBody
    public Map<String, Object> updateMenu(Menu menu) {
        Map<String, Object> result = new HashMap<>();

        // 1.参数校验
        if(menu.getId() == null) {
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.PARAM_ERROR_MSG);
            return  result;
        }

        // 2.执行业务
        try {
            if(menuService.updateMenu(menu) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    /**
     * 菜单导出
     * @param menu
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("export.do")
    public void export(Menu menu, HttpServletRequest request, HttpServletResponse response) throws Exception {

        OutputStream outputStream = null;

        try {

            // 1.查询菜单列表
//            List<Menu> menuList = menuService.getMenuListByPage(menu);
            List<Menu> menuList = null;

            String fileName = "菜单报表.xls";
            String userAgent = request.getHeader("USER-AGENT").toLowerCase();
            String outputFileName = fileName;
            if (
                    userAgent.toUpperCase().indexOf("MSIE") > 0) {
                outputFileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (userAgent.toUpperCase().indexOf("IPHONE") > 0) {
                outputFileName = new String(fileName.getBytes(), "ISO-8859-1");
            } else {
                outputFileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            String[] titles = {"菜单名称", "图片路径", "请求路径", "序号"};

            // 2.导出excel，需要标题栏，需要数据
            HSSFWorkbook wb = menuService.menuExport(titles, menuList);

            response.setContentType("application/octet-stream");
            // 以附件的形式下载
            response.setHeader("Content-disposition", "attachment; filename=\"" + outputFileName + "\"");

            outputStream = response.getOutputStream();
            wb.write(outputStream);

            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("upload.do")
    @ResponseBody
    public void upload(@RequestParam("multipartFile") MultipartFile multipartFile) throws Exception {
        // 获得文件类型
        String contentType = multipartFile.getContentType();
        System.out.println(contentType);
        if(contentType.contains("jpg") || contentType.contains("jpeg") || contentType.contains("png")) {
            // 获得文件名
            String fileName = "weixinpicture.jpeg";
            File file = new File("/Users/sunjinghao/Desktop/" + fileName);
            if(!file.exists() || file.isDirectory()) {
                file.mkdirs();
            }
            multipartFile.transferTo(file);
        }
    }
}
